package cn.jbolt.ec.wx;

import cn.hutool.http.HttpUtil;
import cn.jbolt.common.model.BecApp;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Inject;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialUploadResult;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

public class QrcodeService {
    @Inject
    CommonService commonService;

    WxMpService wxMpService = GenService.getWxMpService("jmd");


    private final static BecApp becApp;
    private final String temp = "{ \"action_name\": \"QR_LIMIT_SCENE\"," +
            " \"action_info\": {\"scene\": " +
            "{\"scene_id\": \"%d\"}}}";  //永久二维码

    static {
        becApp = GenService.getApp();

    }

    public  String getParamQrcodeUrl(int spreader_id){
        String accessToken;
        try{
             accessToken = wxMpService.getAccessToken();

        }catch (Exception e){
            return null;
        }


        String ticket_url=becApp.getOtherCfgStr7()+accessToken;

        String res = HttpUtil.post(ticket_url,String.format(temp,spreader_id));
        System.out.println(res);
        JSONObject jo = JSONObject.parseObject(res);
        if(jo!=null){
            return jo.getString("ticket");
        }
        return null;
    }

    /**
     * 获取带头像的二维码

     * @param
     * @param openid
     * @return
     */
    public  WxMpMaterialUploadResult getSpreaderQrcodeMediaId(
            Integer spreader_id, String openid){


        WxMpUser wxMpUser = commonService.user_info(openid);

        String headImgUrl= wxMpUser.getHeadImgUrl();

        String qrcodeUrl=becApp.getOtherCfgStr6()+getParamQrcodeUrl(spreader_id);
        return QrCodeCreateUtil.QrCodeWithHeadImage(wxMpService,openid,qrcodeUrl,headImgUrl,becApp);

    }
}
